const Koa = require('koa') // 引入 koa
const Router = require('koa-router')
const next = require('next') // nextjs 作为中间件

const dev = process.env.NODE_ENV !== 'production' // 判断是否处于开发者状态
const app = next({ dev }) // 初始化 nextjs，判断它是否处于 dev：开发者状态，还是production: 正式服务状态
const handle = app.getRequestHandler() // 拿到 http 请求的响应

app.prepare().then(() => {
  const server = new Koa() 
  const router = new Router()

  router.get('/a/:id', async (ctx)=>{
    const id = ctx.params.id
    await handle(ctx.req, ctx.res, {
      pathname: '/a',
      query: {id}
    })
    ctx.response = false
  })
  server.use(router.routes())


  server.use(async (ctx, next) => {
    ctx.body = '<span>Koa Render1</span>'
    await next()
  })

  server.use(async (ctx, next) => {
    await handle(ctx.req, ctx.res)
    ctx.response = false
  })

  server.listen(3000, ()=>{
  	console.log('koa server listening on 3000.')
  })
})

